import Table from "../component/Table";
import React from "react";
import { useState } from "react";
import { useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import Tools from "../component/Tools";
import { Typography } from "antd";

function TableList() {
  const [dataSource, setDataSource] = useState([]);
  const navigate = useNavigate();

  let { name } = useParams();

  const fetchData = async () => {
    let data = await window.electronAPI.getTableList({
      name,
    });
    setDataSource(
      data.map((item: any, index: number) => ({
        key: index,
        tableName: item.name,
      }))
    );
  };

  const deleteTable = async (data: any) => {
    await window.electronAPI.deleteTable({
      databaseName: name,
      tableName: data.tableName,
    });
    fetchData;
  };

  const columns = [
    {
      title: "数据表",
      dataIndex: "tableName",
      key: "tableName",
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      render(_: any, record: any) {
        return (
          <Typography.Link
            style={{ marginRight: 8, color: "#fff" }}
            onClick={() => deleteTable(record)}
          >
            Delete
          </Typography.Link>
        );
      },
    },
  ];

  useEffect(() => {
    fetchData();
  }, [name]);

  return (
    <div>
      <Tools
        items={[
          {
            name: "新建数据表",
            onClick: () => {
              navigate("/database/" + name + "/table/form/create");
            },
          },
        ]}
      />
      <Table rowKey="key" dataSource={dataSource} columns={columns} />
    </div>
  );
}

export default TableList;
